package com.abel.quiz.common;/**
 * Created by abel.lin on 2017/11/10.
 */

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.PropertiesEditor;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

/**
 * @author abel.lin
 * @date_time 2017/11/10 16:53
 * @description
 */
public class MyDateEditor extends PropertiesEditor {
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Date date = null;
        if(StringUtils.isNotBlank(text)){
            date = getDate(text);
        }
        setValue(date);
    }

    private Date getDate(String text){
        SimpleDateFormat format = null;
        if(Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$",text)){
            format = new SimpleDateFormat("yyyy-MM-dd");
        }else if(Pattern.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}$",text)){
            format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
        Date date = null;
        try {
            date = format.parse(text);
        } catch (Exception e) {
            try{
                date = new Timestamp(Long.valueOf(text));
            }catch (Exception ex){}
        }
        return date;
    }
}